package com.android.pagemarket.io.protocol.in;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.concurrent.Future;

import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.pagemarket.MyApplication;
import com.android.pagemarket.R;
import com.android.pagemarket.io.protocol.HttpManager;
import com.android.pagemarket.util.FileUtil;
import com.android.pagemarket.util.Log;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-10
 * @see : webservice soap action base
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public abstract class HttpAction<T>
{
    private static final String TAG = "HttpAction";
    /** 网络异常 */
    public static final int ERR_NETWORK = 0;
    /** 服务数据异常 */
    public static final int ERR_SERVER  = 1;
    
    public  static final String host = "http://www.tongzhoudg.com/tzapp/";
    private static final String path = host + "client/tongzhou.do?method=";
    private String  url;
    private HashMap<String, String> params;
    
    protected JSONObject infoJsonObject;
    
    private ActionListener<T> listener;

    private Future<?> future;

    protected T result;
    private boolean isLoading = false;
    
    protected abstract T parseJson(String response) throws Exception;

    public HttpAction(String method)
    {
        if( method != null )
        {
            url = path + method;
            addParam("encoder", "false");
        }
    }

    public void setActionListener(ActionListener<T> listener)
    {
        this.listener = listener;
    }

    public void setFuture(Future<?> furture)
    {
        this.future = furture;
    }

    public void cancel(boolean mayInterruptIfRunning)
    {
        if (future != null && !future.isCancelled())
        {
            future.cancel(mayInterruptIfRunning);
        }
    }
    
    public boolean isLoading()
    {
        return isLoading;
    }

    public void onFinish(String response)
    {
        isLoading = false;
        try {            
            // 有结果
            Log.i(TAG, response);
            result = parseJson(response);
            if (listener != null)
            {
                MyApplication.getContext().mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.onSucceed(result);
                    }
                });
            }
        }catch(Exception e)
        {
            e.printStackTrace();
            onError(ERR_SERVER);
        }
    }
    
    public void onFinish(InputStream response)
    {
        isLoading = false;
        try {            
             // 有结果
            Log.i(TAG, response != null ? response.toString() : "null");
            String filepath = FileUtil.getExternDir(File.separator + "pagemarket" + File.separator + System.currentTimeMillis());
            if( FileUtil.saveFile(filepath, response))
            {
                result = parseJson(filepath);
            }else
            {
                result = null;
            }
            if (listener != null)
            {
                MyApplication.getContext().mHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listener.onSucceed(result);
                    }
                });
            }
        }catch(Exception e)
        {
            e.printStackTrace();
            onError(ERR_SERVER);
        }
    }

    public void onError(final int code)
    {
        isLoading = false;
        if (listener != null)
        {
            MyApplication.getContext().mHandler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    listener.onError(code);
                }
            });
        }
    }

    public String getAction()
    {
        return url;
    }

    public boolean isValid()
    {
        return true;
    }
    
    public boolean isHttpGet()
    {
        return false;
    }
    
    public boolean isFile()
    {
        return false;
    }
    
    /** 添加 SOAP协议的参数 */
    protected void addParam(String param, String value)
    {
        if (param == null || param.trim().length() == 0 || value == null) { return; }
        if (params == null)
        {
            params = new HashMap<String, String>();
        }
        params.put(param, value);
    }
    
    /** 添加JSON协议的参数 
     *  如果 value 为null，则移除 这个参数*/
    protected boolean addJsonParam(String param, Object value)
    {
        if (param == null || param.trim().length() == 0) { return false; }
        if(infoJsonObject == null)
        {
            infoJsonObject = new JSONObject();
        }
        try
        {
            if( value != null)
            {
                infoJsonObject.put(param, value);
            }else
            {
                infoJsonObject.remove(param);
            }
            return true;
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        return false;
    }
        
    /** 获取JSON协议的参数 */
    protected Object getJsonParam(String param)
    {
    	if(infoJsonObject == null)
        {
            infoJsonObject = new JSONObject();
            return null;
        }
        try
        {
            if(infoJsonObject.has(param))
            {
                return infoJsonObject.get(param);
            }else
            {
                return null;
            }
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        
        return null;
    }  

    public boolean hasParams()
    {
        return  (infoJsonObject!=null) || (params != null && !params.isEmpty());
    }

    public HashMap<String, String> getMapParams()
    {
        isLoading = true;
        if(infoJsonObject != null)
        {
            addParam("json", infoJsonObject.toString());
            Log.i(TAG, "json=" + infoJsonObject.toString());
        }
        return params;
    }
    
    public HttpEntity getStringEntity()
    {
        isLoading = true;
        StringEntity se = null;
        if(infoJsonObject != null)
        {
            try
            {
                se = new StringEntity(infoJsonObject.toString());
            } catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }
        }
        return se;
    }
  
    // 提价协议
    public void submit()
    {
        HttpManager.getInstance().submitAction(this);
    }
    
    /** 接口都运行在UI祝线程中*/
    public interface ActionListener<T>
    {
        /** 成功 ，result != null,则有数据，否则返回空值*/
        public void onSucceed(T result);

        /** 错误 ，父类有 Toast 提示,如不需要提示，则子类复写该方法 */
        public void onError(int resultCode);
    }

    public static String getErrorMean(int code)
    {
        int mean = 0;
        switch(code)
        {
            case ERR_NETWORK:
            {
                mean = R.string.tip_network_exception;
                break;
            }
            case ERR_SERVER:
            {
                mean = R.string.tip_server_exception;
                break;
            }
        }
        
        return mean != 0 ? MyApplication.getContext().getString(mean) : "unknown";
    }
}
